package servlets;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entityJPA.Candidate;
import service.CandidateService;

/**
 * Servlet implementation class downloadCvServlet
 */
@WebServlet("/downloadCvServlet")
public class DownloadCvServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	private CandidateService candServ;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadCvServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 * method used to download a cv from a candidate the format used is PDF
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try{
			//get user
			Candidate c=candServ.getCandidateById(Integer.parseInt(request.getParameter("idCandidate")));
			byte[] cv=c.getCvUpload();
			//if there is no cv uploaded for this user then no download dialog is shown
			if(cv.length!=0){
		        ServletOutputStream outStream = response.getOutputStream();
		        response.setContentType("pdf");
		        response.setContentLength(cv.length);
		        response.setHeader("Content-Disposition", "attachment; filename=\"" + "cv" + "\"");
		 
		        outStream.write(cv, 0,cv.length);
	
			}
			response.sendRedirect("/jt-hr-WEB/candidate/candidateDisplay.jsp");


		}catch(Exception e){

		}
	}

}
